﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;

using SBPweb.PlAzureNet.Server.Data.Actors;
using SBPweb.PlAzureNet.Server.Data.Context;

using SBPweb.PlAzureNet.Server.Library.Operations;

namespace SBPweb.PlAzureNet.Server.Library.Services
{

    partial class DataService : ILeagueDataServiceContract
    {

        public IEnumerable<League> FetchAllAdHocLeaguesByPersonId(long personId)
        {
            throw new NotImplementedException();
        }

        public League FetchOneLeagueByExactLocation(Location location)
        {
            return FetchOneLeagueByExactLocationId(location.Id);
        }

        public League FetchOneLeagueByExactLocationId(long locationId)
        {
            using (var context = DataTablesContext.CreateContextInstance())
            {
                return context.Leagues.FirstOrDefault(x => x.LocationId == locationId).GetTranslated(context);
            }
        }

        public IEnumerable<League> FetchAllLeaguesNearByLocation(Location location)
        {
            return FetchAllLeaguesNearByLocationId(location.Id);
        }

        public IEnumerable<League> FetchAllLeaguesNearByLocationId(long locationId)
        {
            throw new NotImplementedException();
        }

        public League FetchOneLeagueById(long leagueId)
        {
            using (var context = DataTablesContext.CreateContextInstance())
            {
                return context.Leagues.FirstOrDefault(x => x.Id == leagueId).GetTranslated(context);
            }
        }

        public League FetchOneLeagueByName(string leagueName, string cultureCode)
        {
            using (var context = DataTablesContext.CreateContextInstance())
            {
                string ci = GetCurrentContextCulture().Name;

                if (string.IsNullOrEmpty(cultureCode))
                {
                    cultureCode = ci;
                }

                var trans = context.Translations.FirstOrDefault(x => x.CultureCode == cultureCode && x.Value == leagueName);
                if (trans == null)
                {
                    return null;
                }

                return context.Leagues.FirstOrDefault(x => x.NameId == trans.TermId).GetTranslated(context);
            }
        }
        
    }

}